/**
 * 
 */
package be.jaisy.osgi.console.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;

import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.log.LogEntry;
import org.osgi.service.log.LogReaderService;

import be.jaisy.osgi.console.service.api.ILogReaderService;
import be.jaisy.osgi.console.service.api.to.LogEntryTo;
import be.jaisy.osgi.console.service.util.ConsoleHelper;

/**
 * @author Stany Blanvalet
 *
 */
public class LogReaderServiceImpl implements ILogReaderService {

	private BundleContext context;
	
	protected void activate(ComponentContext cc) {
		this.context = cc.getBundleContext();
	}

	protected void deactivate(ComponentContext context) throws Exception {
		this.context = null;
	}
	
	private LogReaderService logReaderService;

	public void setLogReaderService(LogReaderService logReaderService) {
		this.logReaderService = logReaderService;
	}

	public void unSetLogReaderService(LogReaderService logReaderService) {
		this.logReaderService = null;
	}

	@SuppressWarnings("unchecked")
	public Collection<LogEntryTo> listLog() {
		if(context==null)
			throw new IllegalStateException("Service not initialized with ComponentContext");
		if(this.logReaderService==null)
			throw new IllegalStateException("LogReaderService not initialized with ComponentContext");
		Collection<LogEntryTo> logEntryTos = new ArrayList<LogEntryTo>();
		Enumeration<LogEntry> logEntrys = this.logReaderService.getLog();
		while(logEntrys.hasMoreElements()){
			logEntryTos.add(ConsoleHelper.convert(logEntrys.nextElement()));
		}
		return logEntryTos;
	}

	@SuppressWarnings("unchecked")
	public Collection listNewLog(LogEntryTo logEntryTo) {
		if(context==null)
			throw new IllegalStateException("Service not initialized with ComponentContext");
		if(this.logReaderService==null)
			throw new IllegalStateException("LogReaderService not initialized with ComponentContext");
		Collection<LogEntryTo> logEntryTos = new ArrayList<LogEntryTo>();
		Enumeration<LogEntry> logEntrys = this.logReaderService.getLog();
		while(logEntrys.hasMoreElements()){
			LogEntryTo item = ConsoleHelper.convert(logEntrys.nextElement());
			if(logEntryTo!=null && logEntryTo.equals(item)){
				return logEntryTos;
			}				
			logEntryTos.add(item);
		}
		return logEntryTos;
	}
	

	
}
